package com.hz.wjy.service.impl;

import com.hz.wjy.helper.StringHelper;
import com.hz.wjy.mapper.UserMapper;
import com.hz.wjy.model.entiy.UserEntiy;
import com.hz.wjy.service.UserService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl implements UserService {

    @Resource
    UserMapper userMapper;

    @Resource
    RedisTemplate redisTemplate;


    @Override
    public void addUser(String username, String password, String realname, String schoolId, int userType) {
        UserEntiy userEntiy = new UserEntiy();
        userEntiy.setUsername(username);
        userEntiy.setRealname(realname);
        userEntiy.setStudent_id(schoolId);
        userEntiy.setUser_type(userType);

        String pwdSalt = UUID.randomUUID().toString().replace("-", "");
        String orginPwd = password + pwdSalt;
        String pwd = StringHelper.md5(orginPwd);

        long pwdValidDate = System.currentTimeMillis() + 7 * 24 * 60 * 60 * 1000;
        userEntiy.setPwd(pwd);
        userEntiy.setPwd_salt(pwdSalt);
        userEntiy.setPwd_valid_date(pwdValidDate);

        userEntiy.setPwd_error_count(0);
        userEntiy.setGrade_id(0);
        userEntiy.setClass_id(0);


        userMapper.addUser(userEntiy);
    }

    @Override
    public void deleteUser(int userId) {

    }

    @Override
    public void findAll() {

    }

    @Override
    public void changePwd() {

    }

    @Override
    public boolean login(String username, String password) {
        // 1,find user by username
        UserEntiy userEntiy = userMapper.findUserByUsername(username);
        if (userEntiy == null) {
            return false;
        }

        // 2,get encrypted password,get pwdSalt
        String pwd = userEntiy.getPwd();
        String pwdSalt = userEntiy.getPwd_salt();

        // 3, password -> encrypted password
        String inputPwd = StringHelper.md5(password + pwdSalt);

        //  4,is password == encrypted password
        if(!pwd.equals(inputPwd)) {
            return false;
        }

        redisTemplate.opsForValue().set("session_" + username, userEntiy.toString(), 10, TimeUnit.MINUTES);
        return true;

    }

    @Override
    public boolean isLogin(String username) {
        return redisTemplate.opsForValue().get("session_" + username) != null;
    }
}
